package com.finger.forest;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.android.tu.loadingdialog.LoadingDailog;
import com.finger.forest.base.BaseActivity;
import com.finger.forest.base.BaseView;
import com.finger.forest.base.CommonKey;
import com.finger.forest.base.ResponseTag;
import com.finger.forest.http.presenter.RegisterPresenter;
import com.finger.forest.model.FzHotspot;
import com.finger.forest.utils.ClickUtils;
import com.finger.forest.utils.DateUtil;
import com.finger.forest.utils.FileBitmapUtils;
import com.finger.forest.utils.ThumbnailUtils;
import com.finger.forest.utils.ToastUtils;
import com.finger.forest.utils.VoiceWidthUtil;
import com.finger.forest.utils.encode.PrefsUtil;
import com.finger.forest.utils.record.AudioRecorder;
import com.finger.forest.utils.record.PcmToWav;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static android.view.View.generateViewId;

/**
 * @author jzj
 * @date 2021/1/23
 * @desc 核查反馈
 */
public class HotCheckFeedbackActivity extends BaseActivity<RegisterPresenter> implements View.OnClickListener, BaseView {

    private static final String TAG = "HotCheckFeedbackAct";

    private static final int REQUEST_SELECT_TYPE = 0;

    /**
     * 返回
     */
    @BindView(R.id.btn_back)
    ImageView backIv;

    /**
     * 保存
     */
    @BindView(R.id.btn_save_patrol)
    Button savePatrolBtn;

    /**
     * 拍照
     */
    @BindView(R.id.tv_camera)
    TextView cameraTv;

    /**
     * 存放拍照图片布局
     */
    @BindView(R.id.layout_photo)
    LinearLayout photoLayout;

    /**
     * 存放视频缩略图布局
     */
    @BindView(R.id.layout_vedio)
    LinearLayout vedioLayout;

    /**
     * 位置
     */
    @BindView(R.id.layout_location)
    LinearLayout locationLayout;

    /**
     * 位置值
     */
    @BindView(R.id.tv_location)
    TextView locationTv;

    /**
     * 类型值
     */
    @BindView(R.id.tv_patrol_type_value)
    TextView patrolTypeValueTv;

    /**
     * 备注
     */
    @BindView(R.id.et_remark)
    EditText remarkEt;

    /**
     * 存放录音布局
     */
    @BindView(R.id.layout_sound)
    LinearLayout soundLayout;

    /**
     * 编辑图片
     */
    @BindView(R.id.tv_edit_photo)
    TextView editPhotoTv;

    /**
     * 编辑视频
     */
    @BindView(R.id.tv_edit_vedio)
    TextView editVedioTv;

    /**
     * 录音
     */
    @BindView(R.id.tv_sound_record)
    TextView soundRecordTv;

    /**
     * 录制视频
     */
    @BindView(R.id.tv_vedio)
    TextView vedioTv;

    //pcm文件
    private File file;

    MediaRecorder mr;
    TimerTask task;
    Timer timer = new Timer();

    MediaRecorder mRecorder;

    /**
     * 存放图片路径List
     */
    List<String> imageFilePathList = new ArrayList<>();

    /**
     * 存放语音路径List
     */
    List<String> voiceFilePathList = new ArrayList<>();
    private static String voiceFilePathTemp = ""; //语音文件路径

    /**
     * 存放视频路径List
     */
    List<String> vedioFilePathList = new ArrayList<>();

    private final int CAMERA_REQUEST = 1111;
    private final int VIDEO_CAMERA_REQUEST = 2222;
    private final int SELECT_LOCATION_REQUEST = 3333;

    /*Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //main_text.setText("下载完成");
            System.out.println(new Date().toString());
        }
    };*/
    private boolean isRecording = false;

    private long voiceStartTime = 0;

    LayoutInflater factory = null;

    LoadingDailog.Builder loadBuilder = null;
    LoadingDailog dialog = null;

    //经度
    private String longitude;

    //纬度
    private String latitude;

    //热点ID
    private String hId;

    //热点编号
    private String hHotspotNo;

    AudioRecorder audioRecorder;

    @Override
    protected int setView() {
        return R.layout.activity_hot_check_feedback;
    }

    @Override
    protected void receiveData() {
        //接收参数
        Intent intent=getIntent();
        hId = intent.getStringExtra("hId");

        Map<String, Object> maps = new HashMap<>();
        maps.put("Id",hId);
        presenter.queryHotDetail(maps);//查询热点核查详情
    }

    @Override
    protected void initializeView() {

        audioRecorder = AudioRecorder.getInstance();

        factory = LayoutInflater.from(HotCheckFeedbackActivity.this);

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        loadBuilder=new LoadingDailog.Builder(this)
                .setMessage("上传中...")
                .setCancelable(false)
                .setCancelOutside(true);

        /*soundRecordTv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Log.e("xxx","按下");
                        voiceStartTime = new Date().getTime(); //初始化录音开始时间
                        Thread thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                StartRecord();
                                Log.e(TAG,"start");
                            }
                        });
                        thread.start();
                        soundRecordTv.setText("录音中...");
                        Log.i(TAG,"开始录音");
                        break;
                    case MotionEvent.ACTION_UP:
                        soundRecordTv.setText("按住录音");
                        Log.e("xxx","抬起");
                        isRecording = false;
                        Log.i(TAG,"停止录音");
                        int duration = (int)(new Date().getTime() - voiceStartTime)/1000; //计算录音时间（单位：秒）
                        if (duration <= 0){
                            ToastUtils.show("语音时间太短");
                            break;
                        }

                        //添加语音气泡
                        View layout = factory.inflate(R.layout.patrol_sound_item, null);
                        RelativeLayout soundItemLayout = (RelativeLayout)layout.findViewById(R.id.layout_sound_item);//布局
                        soundItemLayout.setId(generateViewId());
                        soundItemLayout.setTag(voiceFilePathTemp.substring(voiceFilePathTemp.lastIndexOf("/")));
                        ImageView soundRecordTv = (ImageView)layout.findViewById(R.id.tv_sound_record_item);//语音气泡
                        ViewGroup.LayoutParams soundRecordTv_params = soundRecordTv.getLayoutParams();
                        soundRecordTv_params.width = VoiceWidthUtil.calVoiceWidth(duration);//计算气泡宽度
                        soundRecordTv.setLayoutParams(soundRecordTv_params);//设置语音气泡宽度
                        TextView voiceSecondTv = (TextView)layout.findViewById(R.id.tv_voice_second);//语音秒数
                        voiceSecondTv.setText(duration+"''");
                        soundRecordTv.setOnClickListener(HotCheckFeedbackActivity.this);
                        ImageView deleteIv = (ImageView)layout.findViewById(R.id.iv_delete_sound);//删除
                        deleteIv.setOnClickListener(HotCheckFeedbackActivity.this);

                        soundLayout.addView(soundItemLayout);
                        //添加语音文件
                        voiceFilePathList.add(voiceFilePathTemp);
                        break;
                }
                return true;
            }
        });*/

        soundRecordTv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        Log.e("xxx", "按下");
                        voiceStartTime = new Date().getTime(); //初始化录音开始时间
                        soundRecordTv.setText("录音中...");
                        Log.i(TAG, "开始录音");

                        //初始化录音
                        String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
                        audioRecorder.createDefaultAudio(fileName);
                        audioRecorder.startRecord(null);
                        break;
                    case MotionEvent.ACTION_UP:
                        Log.i(TAG, "停止录音");
                        soundRecordTv.setText("按住录音");
                        int duration = (int) (new Date().getTime() - voiceStartTime) / 1000; //计算录音时间（单位：秒）
                        if (duration <= 0) {
                            ToastUtils.show("语音时间太短");
                            break;
                        }

                        voiceFilePathTemp = AudioRecorder.filePath;
                        //停止录音
                        audioRecorder.stopRecord();

                        //pcm转wav
                        mergePCMFilesToWAVFile(new ArrayList<>());
                        //路径由pcm转成wav
                        voiceFilePathTemp = voiceFilePathTemp.substring(0,voiceFilePathTemp.lastIndexOf("."))+".wav";

                        //添加语音气泡
                        View layout = factory.inflate(R.layout.patrol_sound_item, null);
                        RelativeLayout soundItemLayout = (RelativeLayout) layout.findViewById(R.id.layout_sound_item);//布局
                        soundItemLayout.setId(generateViewId());
                        soundItemLayout.setTag(voiceFilePathTemp.substring(voiceFilePathTemp.lastIndexOf("/")+1));
                        ImageView soundRecordTv = (ImageView) layout.findViewById(R.id.tv_sound_record_item);//语音气泡
                        ViewGroup.LayoutParams soundRecordTv_params = soundRecordTv.getLayoutParams();
                        soundRecordTv_params.width = VoiceWidthUtil.calVoiceWidth(duration);//计算气泡宽度
                        soundRecordTv.setLayoutParams(soundRecordTv_params);//设置语音气泡宽度
                        TextView voiceSecondTv = (TextView) layout.findViewById(R.id.tv_voice_second);//语音秒数
                        voiceSecondTv.setText(duration + "''");
                        soundRecordTv.setOnClickListener(HotCheckFeedbackActivity.this);
                        ImageView deleteIv = (ImageView) layout.findViewById(R.id.iv_delete_sound);//删除
                        deleteIv.setOnClickListener(HotCheckFeedbackActivity.this);

                        soundLayout.addView(soundItemLayout);
                        //添加语音文件
                        voiceFilePathList.add(voiceFilePathTemp);
                        break;
                }
                return true;
            }
        });
    }

    /**
     * 将pcm合并成wav
     *
     * @param filePaths
     */
    private void mergePCMFilesToWAVFile(final List<String> filePaths) {
        String toFilePath = voiceFilePathTemp.substring(0,voiceFilePathTemp.lastIndexOf("."))+".wav";
        filePaths.add(voiceFilePathTemp);
        Log.i(TAG,"pcm转wav文件开始======》");
        Log.i(TAG,"pcm文件："+voiceFilePathTemp);
        Log.i(TAG,"wav文件："+toFilePath);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (PcmToWav.mergePCMFilesToWAVFile(filePaths, toFilePath)) {
                    //操作成功
                } else {
                    //操作失败
                    Log.e("AudioRecorder", "mergePCMFilesToWAVFile fail");
                    throw new IllegalStateException("mergePCMFilesToWAVFile fail");
                }
            }
        }).start();
    }

    @Override
    protected void loadDataFromServer() {

    }

    @Override
    public void onSuccess(Object model, int tag, String msg) {

        switch (tag) {
            //返回
            case ResponseTag.CHECK_FEED_BACK:
                //隐藏关闭加载等待
                dialog.hide();
                dialog.dismiss();
                ToastUtils.show(msg == null ? " " : msg);
                finish();
                break;

            //热点核查详情
            case ResponseTag.QUERY_HOT_DETAIL:
                FzHotspot hotDetail = (FzHotspot) model;
                longitude = hotDetail.gethLongitude().toString();
                latitude = hotDetail.gethLatitude().toString();
                hHotspotNo = hotDetail.gethHotspotNo();
                locationTv.setText(longitude+"，"+latitude);
                patrolTypeValueTv.setText(hHotspotNo);
                break;

            default:
                break;
        }
    }

    @Override
    public void onError(int errcode, int tag, String message) {

    }

    @OnClick({R.id.btn_back, R.id.btn_save_patrol, R.id.tv_camera, R.id.tv_edit_photo, R.id.layout_location, R.id.tv_vedio, R.id.tv_edit_vedio })
    @Override
    public void onClick(View v) {
        if (ClickUtils.isFastClick()) { //防止重复点击
            switch (v.getId()) {

                //返回
                case R.id.btn_back:
                    finish();
                    break;

                //保存
                case R.id.btn_save_patrol:
                    if (locationTv.getText().toString().equals("")){
                        ToastUtils.show("请选择位置");
                    } else {
                        String remark = remarkEt.getText().toString();
                        String[] locationSplit = locationTv.getText().toString().split("，");

                        Map<String, RequestBody> bodyMap = new HashMap<>();
                        bodyMap.put("hId", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), hId));
                        bodyMap.put("hHotspotNo", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), hHotspotNo));
                        bodyMap.put("hRecordBy", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"),
                                PrefsUtil.getString(HotCheckFeedbackActivity.this, CommonKey.USER_ID)));
                        bodyMap.put("hLongitude", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), ""+locationSplit[0]));
                        bodyMap.put("hLatitude", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), ""+locationSplit[1]));
                        bodyMap.put("hCondition", RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"), ""+remark));

                        //封装图片集合
                        List<MultipartBody.Part> listFile = new ArrayList<>();
                        for (int i=0; i<imageFilePathList.size(); i++){
                            String filePath_ = imageFilePathList.get(i);
                            File fileTemp = new File(filePath_);
                            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), fileTemp);
                            MultipartBody.Part requestImgPart =
                                    MultipartBody.Part.createFormData("imageFile", filePath_.substring(filePath_.lastIndexOf("/")+1,filePath_.length()), requestFile);
                            listFile.add(requestImgPart);
                        }

                        //封装语音集合
                        List<MultipartBody.Part> listFileVoice = new ArrayList<>();
                        for (int i=0; i<voiceFilePathList.size(); i++){
                            String filePath_ = voiceFilePathList.get(i);
                            File fileTemp = new File(filePath_);
                            RequestBody requestFile = RequestBody.create(MediaType.parse("audio/PCMA"), fileTemp);
                            MultipartBody.Part requestImgPart =
                                    MultipartBody.Part.createFormData("voiceFile", filePath_.substring(filePath_.lastIndexOf("/")+1,filePath_.length()), requestFile);
                            listFileVoice.add(requestImgPart);
                        }

                        //封装视频集合
                        List<MultipartBody.Part> listFileVedio = new ArrayList<>();
                        for (int i=0; i<vedioFilePathList.size(); i++){
                            String filePath_ = vedioFilePathList.get(i);
                            File fileTemp = new File(filePath_);
                            RequestBody requestFile = RequestBody.create(MediaType.parse("video/mp4"), fileTemp);
                            MultipartBody.Part requestImgPart =
                                    MultipartBody.Part.createFormData("videoFile", filePath_.substring(filePath_.lastIndexOf("/")+1,filePath_.length()), requestFile);
                            listFileVedio.add(requestImgPart);
                        }

                        dialog=loadBuilder.create();
                        //显示加载等待
                        //dialog.show();
                        presenter.checkFeedBack(bodyMap, listFile, listFileVoice, listFileVedio);
                    }

                    break;

                //拍照
                case R.id.tv_camera:
                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                    break;

                //录制视频
                case R.id.tv_vedio:
                    Intent vedioIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                    Uri fileUri = null;
                    try {
                        fileUri = Uri.fromFile(createMediaFile()); //创建保存文件
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //设置文件名称
                    vedioIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                    //设置视频录制的最长时间
                    //vedioIntent.putExtra (MediaStore.EXTRA_DURATION_LIMIT,30);
                    //设置视频录制的画质
                    vedioIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                    startActivityForResult(vedioIntent, VIDEO_CAMERA_REQUEST);
                    break;

                //删除图片
                case R.id.iv_delete:
                    //获取父布局
                    RelativeLayout relativeLayout = (RelativeLayout) v.getParent();
                    String tag = relativeLayout.getTag().toString();

                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                            .setMessage("确定删除此照片吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    //删除图片布局
                                    photoLayout.removeView(relativeLayout);
                                    //删除图片集合
                                    for (int j=0; j<imageFilePathList.size(); j++){
                                        if (imageFilePathList.get(j).contains(tag)){
                                            imageFilePathList.remove(j);
                                        }
                                    }
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.cancel();
                                }
                            })
                            .create();
                    alertDialog.show();

                    WindowManager m = getWindowManager();
                    Display d = m.getDefaultDisplay(); //为获取屏幕宽、高
                    WindowManager.LayoutParams p = alertDialog.getWindow().getAttributes(); //获取对话框当前的参数值
                    p.width = (int) (d.getWidth() * 0.7); //宽度设置为屏幕的0.8
                    alertDialog.getWindow().setAttributes(p); //设置生效
                    break;

                //删除视频
                case R.id.iv_delete_vedio:
                    //获取父布局
                    RelativeLayout relativeLayout1 = (RelativeLayout) v.getParent();
                    String tag1 = relativeLayout1.getTag().toString();

                    AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                            .setMessage("确定删除此视频吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    //删除视频布局
                                    vedioLayout.removeView(relativeLayout1);
                                    //删除视频集合
                                    for (int j=0; j<vedioFilePathList.size(); j++){
                                        if (vedioFilePathList.get(j).contains(tag1)){
                                            vedioFilePathList.remove(j);
                                        }
                                    }
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.cancel();
                                }
                            })
                            .create();
                    alertDialog1.show();

                    WindowManager m1 = getWindowManager();
                    Display d1 = m1.getDefaultDisplay(); //为获取屏幕宽、高
                    WindowManager.LayoutParams p1 = alertDialog1.getWindow().getAttributes(); //获取对话框当前的参数值
                    p1.width = (int) (d1.getWidth() * 0.7); //宽度设置为屏幕的0.8
                    alertDialog1.getWindow().setAttributes(p1); //设置生效
                    break;

                //编辑图片
                case R.id.tv_edit_photo:
                    int childCount = photoLayout.getChildCount();
                    if (childCount > 0) {
                        int visibility = View.INVISIBLE;
                        for (int i = 0; i < childCount; i++) {
                            RelativeLayout relativeLayout2 = (RelativeLayout) photoLayout.getChildAt(i);
                            ImageView deleteIv = (ImageView) relativeLayout2.getChildAt(1);
                            if (i == 0) {
                                visibility = deleteIv.getVisibility();
                            }
                            if (visibility == View.INVISIBLE) {
                                deleteIv.setVisibility(View.VISIBLE);
                            } else {
                                deleteIv.setVisibility(View.INVISIBLE);
                            }
                        }
                    }
                    break;

                //编辑视频
                case R.id.tv_edit_vedio:
                    int childCount1 = vedioLayout.getChildCount();
                    if (childCount1 > 0) {
                        int visibility = View.INVISIBLE;
                        for (int i = 0; i < childCount1; i++) {
                            RelativeLayout relativeLayout3 = (RelativeLayout) vedioLayout.getChildAt(i);
                            ImageView deleteIv = (ImageView) relativeLayout3.getChildAt(1);
                            if (i == 0) {
                                visibility = deleteIv.getVisibility();
                            }
                            if (visibility == View.INVISIBLE) {
                                deleteIv.setVisibility(View.VISIBLE);
                            } else {
                                deleteIv.setVisibility(View.INVISIBLE);
                            }
                        }
                    }
                    break;

                //播放语音
                case R.id.tv_sound_record_item:
                    String voiceFilePath = ((RelativeLayout)v.getParent()).getTag().toString();
                    String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                            + "/Forest/voice/"+voiceFilePath;
                    PlayRecordWav(filePath);
                    //PlayRecord(filePath);
                    Log.i(TAG, "播放录音");
                    break;

                //删除语音
                case R.id.iv_delete_sound:
                    //获取父布局
                    RelativeLayout relativeLayout4 = (RelativeLayout) v.getParent();
                    String tag4 = relativeLayout4.getTag().toString();

                    AlertDialog alertDialog4 = new AlertDialog.Builder(this)
                            .setMessage("确定删除此录音吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    //删除语音界面
                                    soundLayout.removeView(relativeLayout4);
                                    //删除语音集合
                                    for (int j=0; j<voiceFilePathList.size(); j++){
                                        if (voiceFilePathList.get(j).contains(tag4)){
                                            voiceFilePathList.remove(j);
                                        }
                                    }
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.cancel();
                                }
                            })
                            .create();
                    alertDialog4.show();

                    WindowManager m4 = getWindowManager();
                    Display d4 = m4.getDefaultDisplay(); //为获取屏幕宽、高
                    WindowManager.LayoutParams p4 = alertDialog4.getWindow().getAttributes(); //获取对话框当前的参数值
                    p4.width = (int) (d4.getWidth() * 0.7); //宽度设置为屏幕的0.8
                    alertDialog4.getWindow().setAttributes(p4); //设置生效

                    //deleFile();//删除文件
                    break;

                //位置选择跳转
                case R.id.layout_location:
                    /*Intent intent = new Intent(HotCheckFeedbackActivity.this, PatrolLocationActivity.class);
                    startActivityForResult(intent, SELECT_LOCATION_REQUEST);*/
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) {
            return;
        }

        switch (requestCode) {

            //拍照
            case CAMERA_REQUEST:

                Bitmap photoBitmap = (Bitmap) data.getExtras().get("data");
                String fileName = DateUtil.dateToStr(DateUtil.DATE_FORMAT_SS);

                View layout = factory.inflate(R.layout.patrol_photo_item, null);
                RelativeLayout photoItemLayout = (RelativeLayout)layout.findViewById(R.id.layout_photo_item);//布局
                photoItemLayout.setId(generateViewId());
                photoItemLayout.setTag(fileName); //添加Tag，删除时使用
                ImageView photoIv = (ImageView)layout.findViewById(R.id.iv_photo);//图片
                photoIv.setImageBitmap(photoBitmap);
                ImageView deleteIv = (ImageView)layout.findViewById(R.id.iv_delete);//图片
                deleteIv.setOnClickListener(this);

                //保存图片，返回图片路径
                String filePath = FileBitmapUtils.saveBitmapPicture(photoBitmap, fileName+".jpg", context);
                //添加图片路径
                imageFilePathList.add(filePath);

                photoLayout.addView(photoItemLayout);
                break;

            //录制视频
            case VIDEO_CAMERA_REQUEST:

                Uri uri = data.getData();
                Log.e(TAG, "onActivityResult: " + uri.toString());
                String[] split = uri.toString().split(":");
                String vedioFilePath = split[1];
                Bitmap vedioImageBtp = ThumbnailUtils.createVideoThumbnail(vedioFilePath);

                View layoutVedio = factory.inflate(R.layout.patrol_vedio_item, null);
                RelativeLayout photoItemLayout1 = (RelativeLayout)layoutVedio.findViewById(R.id.layout_photo_item);//布局
                photoItemLayout1.setId(generateViewId());
                photoItemLayout1.setTag(vedioFilePath.substring(vedioFilePath.lastIndexOf("/"))); //添加Tag，删除时使用
                ImageView photoIv1 = (ImageView)layoutVedio.findViewById(R.id.iv_photo);//图片
                photoIv1.setImageBitmap(vedioImageBtp);
                ImageView deleteIv1 = (ImageView)layoutVedio.findViewById(R.id.iv_delete_vedio);//图片
                deleteIv1.setOnClickListener(this);

                //添加视频路径
                vedioFilePathList.add(vedioFilePath);

                vedioLayout.addView(photoItemLayout1);
                break;

            //选择类型
            case REQUEST_SELECT_TYPE:
                Bundle bundle = data.getExtras();
                int patrolType = bundle.getInt("patrolType");
                String patrolTypeName = bundle.getString("patrolTypeName");
                patrolTypeValueTv.setText(patrolTypeName);
                patrolTypeValueTv.setTag(patrolType);
                break;

            //选择位置
            case SELECT_LOCATION_REQUEST:
                Bundle bundle1 = data.getExtras();
                String longtitude = bundle1.getString("longtitude");
                String latitude = bundle1.getString("latitude");
                locationTv.setText(longtitude+"，"+latitude);
                break;

        }
    }

    private File createMediaFile() throws IOException {
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/Forest/vedio/");
        if (!mediaStorageDir.exists()) {
            mediaStorageDir.mkdirs();
        }
        String imageFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String suffix = ".mp4";
        File mediaFile = new File(mediaStorageDir, imageFileName + suffix);
        return mediaFile;
    }

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static final int REQUEST_EXTERNAL_STORAGE2 = 2;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO};

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    public static void verifyStoragePermissions2(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.READ_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE2);
        }
    }

    public void PlayRecordWav(String filePah) {
        Log.i(TAG,"播放文件路径："+ filePah);
        MediaPlayer mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(filePah);
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //播放文件
    public void PlayRecord(String filePah) {
        verifyStoragePermissions2(HotCheckFeedbackActivity.this);
        File file = new File(filePah);
        //读取文件
        int musicLength = (int) (file.length() / 2);
        short[] music = new short[musicLength];
        try {
            InputStream is = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            DataInputStream dis = new DataInputStream(bis);
            int i = 0;
            while (dis.available() > 0) {
                music[i] = dis.readShort();
                i++;
            }
            dis.close();
            AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
                    16000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
                    AudioFormat.ENCODING_PCM_16BIT,
                    musicLength * 2,
                    AudioTrack.MODE_STREAM);
            audioTrack.play();
            audioTrack.write(music, 0, musicLength);
            audioTrack.stop();
        } catch (Throwable t) {
            Log.e(TAG, "播放失败");
            t.printStackTrace();
        }
    }

    //删除文件
    private void deleFile() {
        if(file == null){
            return;
        }
        file.delete();
        Log.i(TAG,"文件删除成功");
    }

    //开始录音
    public void StartRecord() {
        verifyStoragePermissions(HotCheckFeedbackActivity.this);
        Log.i(TAG,"开始录音");
        //16K采集率
        int frequency = 16000;
        //格式
        int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
        //16Bit
        int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
        voiceFilePathTemp = Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/Forest/voice/";
        File tempFile = new File(voiceFilePathTemp);
        if (!tempFile.exists()){ //目录不存在，则创建目录
            Log.i(TAG,"目录不存在，创建目录："+voiceFilePathTemp);
            boolean boo = tempFile.mkdirs();
            Log.i(TAG,"目录创建："+boo);
        }

        voiceFilePathTemp += DateUtil.dateToStr(DateUtil.DATE_FORMAT_SS)+".pcm";
        //生成PCM文件
        file = new File(voiceFilePathTemp);
        Log.i(TAG,"生成文件");
        //如果存在，就先删除再创建
        /*if (file.exists())
            file.delete();
        Log.i(TAG,"删除文件");*/
        try {
            file.createNewFile();
            Log.i(TAG,"创建文件");
        } catch (IOException e) {
            Log.i(TAG,"未能创建"+e.getMessage());
            e.printStackTrace();
            throw new IllegalStateException("未能创建" + file.toString());
        }
        try {
            //输出流
            OutputStream os = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(os);
            DataOutputStream dos = new DataOutputStream(bos);
            int bufferSize = AudioRecord.getMinBufferSize(frequency, channelConfiguration, audioEncoding);
            AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, frequency, channelConfiguration, audioEncoding, bufferSize);

            short[] buffer = new short[bufferSize];
            //开始录制音频
            try{
                // 防止某些手机崩溃，例如联想
                audioRecord.startRecording();
            }catch (IllegalStateException e){
                e.printStackTrace();
            }
            Log.i(TAG, "开始录音");
            isRecording = true;
            while (isRecording) {
                int bufferReadResult = audioRecord.read(buffer, 0, bufferSize);
                for (int i = 0; i < bufferReadResult; i++) {
                    dos.writeShort(buffer[i]);
                }
            }
            //停止录制
            try {
                // 防止某些手机崩溃，例如联想
                audioRecord.stop();
                // 彻底释放资源
                audioRecord.release();
                audioRecord = null;
            }catch (IllegalStateException e){
                e.printStackTrace();
            }
            dos.close();
        } catch (Throwable t) {
            Log.e(TAG, "录音失败");
            t.printStackTrace();
        }
    }

}
